#pragma once
#include <functional>
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;
using namespace socket_ns;

using service_io_t = std::function<void(SockSPtr, InetAddr &)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, service_io_t service)
        : _port(port), _service(service), _sock(std::make_shared<TcpSocket>())
    {
        _sock->BuildTcpServerSocket(_port);
    }

    struct ThreadDate
    {
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;
        ThreadDate(SockSPtr sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd), _self(self), _addr(addr) {}
    };

    static void *Execute(void *arg)
    {
        pthread_detach(pthread_self());
        ThreadDate *td = static_cast<ThreadDate *>(arg);
        td->_self->_service(td->_sockfd, td->_addr);
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr newSock = _sock->Accepter(&client);
            if (newSock == nullptr)
                continue;

            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n",
                client.addrStr().c_str(), newSock->Sockfd());

            pthread_t tid;
            pthread_create(&tid, nullptr, Execute,
                           new ThreadDate(newSock, this, client));
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        //_sock->Close();
    }

private:
    uint16_t _port;
    SockSPtr _sock;

    bool _isrunning;
    service_io_t _service;
};